package com.example.service;

import com.example.common.Result;
import com.example.entity.OrganizationActivity;
import com.example.entity.OrganizationBranch;
import com.example.exception.CustomException;
import com.example.mapper.OrganizationActivityMapper;
import com.example.mapper.OrganizationBranchMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class OrganizationActivityService {

    private static final Logger log = LoggerFactory.getLogger(OrganizationActivityService.class);

    @Resource
    private OrganizationActivityMapper organizationActivityMapper;
    @Resource
    private OrganizationBranchMapper organizationBranchMapper;

    /**
     * 验证用户是否有权限操作该支部的活动
     */
    private void validateBranchPermission(Long leaderId, Long branchId) {
        OrganizationBranch branch = organizationBranchMapper.selectById(branchId);
        if (branch == null) {
            throw new CustomException("支部不存在");
        }
        if (!leaderId.equals(branch.getLeaderId())) {
            throw new CustomException("您没有权限在该支部发布活动");
        }
    }

    /**
     * 新增活动
     */
    @Transactional
    public Result add(OrganizationActivity activity, Long leaderId) {
        validateBranchPermission(leaderId, activity.getBranchId());
        organizationActivityMapper.insert(activity);
        return Result.success();
    }

    /**
     * 更新活动
     */
    @Transactional
    public Result updateById(OrganizationActivity activity, Long leaderId) {
        validateBranchPermission(leaderId, activity.getBranchId());
        organizationActivityMapper.updateById(activity);
        return Result.success();
    }

    public void deleteById(Long id) {
        organizationActivityMapper.deleteById(id);
    }

    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            this.deleteById(Long.valueOf(id));
        }
    }

    public OrganizationActivity selectById(Long id) {
        return organizationActivityMapper.selectById(id);
    }

    public List<OrganizationActivity> selectAll(OrganizationActivity activity) {
        return organizationActivityMapper.selectAll(activity);
    }

    public PageInfo<OrganizationActivity> selectPage(OrganizationActivity activity, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<OrganizationActivity> list = organizationActivityMapper.selectAll(activity);
        return new PageInfo<>(list);
    }
}
